package com.dingjust.tools.pdf;

import com.dingjust.tools.pdf.dto.AgreementDto;
import com.dingjust.tools.pdf.provider.AsianFontProvider;
import com.dingjust.tools.pdf.style.DefaultStyle;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import lombok.extern.log4j.Log4j2;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.StringTemplateResourceLoader;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.parser.Parser;
import org.jsoup.select.Elements;
import org.pegdown.Extensions;
import org.pegdown.PegDownProcessor;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Log4j2
public class MarkdownToPdf {
    private static final String UNIT = "万千佰拾亿千佰拾万千佰拾元角分";
    private static final String DIGIT = "零壹贰叁肆伍陆柒捌玖";
    private static final double MAX_VALUE = 9999999999999.99D;
    private static String FONT_PATH;
    private static String BD_FONT_PATH;
    private final static Charset charset = Charset.forName("GBK");
    final static String[] colWidth = {"12%", "12%", "10%", "8%", "8%", "8%", "12%", "10%", "10%", "10%"};


    public MarkdownToPdf(String fontPath,String bdFontPath) {
        this.FONT_PATH = fontPath;
        this.BD_FONT_PATH = bdFontPath;
    }


    public static String getTemplateString(String template, Object data){
        StringTemplateResourceLoader resourceLoader = new StringTemplateResourceLoader();
        Configuration cfg = null;
        try {
            cfg = Configuration.defaultConfiguration();
        } catch (IOException e) {
            e.printStackTrace();
        }
        GroupTemplate gt = new GroupTemplate(resourceLoader, cfg);
        Template t = gt.getTemplate(template);
        Map map = new HashMap();
        map.put("data",data);
        t.binding(map);
        return t.render();
    }
    public void create(List<File> fileList, OutputStream outputStream) throws Exception{
            Document document = new Document(PageSize.A4);

            PdfWriter pdfWriter = PdfWriter.getInstance(document,
                    outputStream);

            document.open();
//            document.addAuthor("1+1");
//            document.addCreator("1+1");
//            document.addSubject("电子合同");
            document.addCreationDate();
//            document.addTitle("电子合同");
            fileList.stream().forEach(file->{
                try {
                    Image image = Image.getInstance(file.getAbsolutePath());
                    float documentWidth = document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin();
                    float documentHeight = document.getPageSize().getHeight()-document.topMargin()-document.bottomMargin();
//                    float documentHeight = documentWidth / 580 * 320;//重新设置宽高
                    if(image.getWidth()>documentWidth){
//                        documentWidth/image.getWidth()*image.getHeight()
                        image.scaleToFit(documentWidth,documentHeight);//重新设置宽高
                    }

                    document.add(image);
                } catch (Exception ex) {

                }


            });

            document.close();



    }

    public void merge(List<File> files,OutputStream outputStream) throws Exception{
        Document document = null;
        document = new Document(new PdfReader(files.get(0).getAbsolutePath()).getPageSize(1));
        PdfCopy copy = new PdfCopy(document, outputStream);
        document.open();
        for (int i = 0; i < files.size(); i++) {
            PdfReader reader = new PdfReader(files.get(i).getAbsolutePath());
            int n = reader.getNumberOfPages();
            for (int j = 1; j <= n; j++) {
                document.newPage();
                PdfImportedPage page = copy.getImportedPage(reader, j);
                copy.addPage(page);
            }
        }
        document.close();
        outputStream.close();



    }

    public void create(String templateString,String extraHtml, OutputStream outputStream, AgreementDto dto) throws Exception{
            Document document = new Document(PageSize.A4);

            PdfWriter pdfWriter = PdfWriter.getInstance(document,
                    outputStream);

            document.open();
//            document.addAuthor("1+1");
//            document.addCreator("1+1");
//            document.addSubject("电子合同");
            document.addCreationDate();
//            document.addTitle("电子合同");

            XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
            String mdContent = templateString;
            PegDownProcessor pdp = new PegDownProcessor(Extensions.ALL);
            mdContent = getTemplateString(mdContent,dto);
            String htmlContent = "<html lang=\"en\"><meta http-equiv=\"Content-Type\" content=\"text/html; charset="+charset.name()+"\" /><body>" + pdp.markdownToHtml(mdContent) + "</body></html>";
            org.jsoup.nodes.Document htmlDoc = Jsoup.parse(htmlContent, "", Parser.xmlParser());
            Element element = htmlDoc.selectFirst("table");
            Elements centerEle = htmlDoc.select("center");
            //处理center标签
            if(centerEle!=null){
                for(Element center:centerEle){
                    Element parent = center.parent();
                    String text = center.text();
                    center.remove();
                    parent.text(text);
                    parent.attr("align","center");
                    parent.attr("style","margin:0 auto;text-align:center;");
                }

            }
            if(element!=null){
                //处理表格宽度问题
                Elements elements = element.select("th");
                for (int i = 0; i < elements.size(); i++) {
                    if (i < colWidth.length) {
                        elements.get(i).attr("width", colWidth[i]);
                    }
                }
            }

            //处理h1~h6问题
            Elements aList = htmlDoc.select("h1 a,h2 a,h3 a,h4 a,h5 a,h6 a");
            for (Element a : aList) {
                String text = a.text();
                a.text("");
                a.appendElement("strong");
                a.child(0).text(text);
            }
            String bodyContent = htmlDoc.select("body").html();
            if(extraHtml!=null){
                bodyContent =  bodyContent + getTemplateString(extraHtml,dto);
                bodyContent = bodyContent.replaceAll("\t","").replaceAll("\n","");
            }
            log.debug("生产pdf原始html内容：{}",htmlDoc.select("body").html());

            worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(bodyContent.getBytes(charset))
                    , new  ByteArrayInputStream(DefaultStyle.DEFAULT_CSS.getBytes())
                    ,charset
                    , new AsianFontProvider(FONT_PATH,BD_FONT_PATH));
            document.close();



    }

    public static void createWithHtml(String templateString,String extraHtml, OutputStream outputStream, Object dto) throws Exception{
//            Document document = new Document(PageSize.A4);
            Document document = new Document(new RectangleReadOnly(1191F,842F));

            PdfWriter pdfWriter = PdfWriter.getInstance(document,
                    outputStream);

            document.open();
//            document.addAuthor("1+1");
//            document.addCreator("1+1");
//            document.addSubject("电子合同");
            document.addCreationDate();
//            document.addTitle("电子合同");

            XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
            String mdContent = templateString;
            PegDownProcessor pdp = new PegDownProcessor(Extensions.ALL);
//            mdContent = getTemplateString(mdContent,dto);
            String htmlContent = "<html lang=\"en\"><meta http-equiv=\"Content-Type\" content=\"text/html; charset="+charset.name()+"\" /><body>" + templateString + "</body></html>";
            org.jsoup.nodes.Document htmlDoc = Jsoup.parse(htmlContent, "", Parser.xmlParser());
/*            Element element = htmlDoc.selectFirst("table");
            Elements centerEle = htmlDoc.select("center");
            //处理center标签
            if(centerEle!=null){
                for(Element center:centerEle){
                    Element parent = center.parent();
                    String text = center.text();
                    center.remove();
                    parent.text(text);
                    parent.attr("align","center");
                    parent.attr("style","margin:0 auto;text-align:center;");
                }

            }*/
/*            if(element!=null){
                //处理表格宽度问题
                Elements elements = element.select("th");
                for (int i = 0; i < elements.size(); i++) {
                    if (i < colWidth.length) {
                        elements.get(i).attr("width", colWidth[i]);
                    }
                }
            }*/

            //处理h1~h6问题
            Elements aList = htmlDoc.select("h1 a,h2 a,h3 a,h4 a,h5 a,h6 a");
            for (Element a : aList) {
                String text = a.text();
                a.text("");
                a.appendElement("strong");
                a.child(0).text(text);
            }
            String bodyContent = htmlDoc.select("body").html();
            if(extraHtml!=null){
                bodyContent =  bodyContent + getTemplateString(extraHtml,dto);
                bodyContent = bodyContent.replaceAll("\t","").replaceAll("\n","");
            }
            log.debug("生产pdf原始html内容：{}",htmlDoc.select("html").html());
        System.out.println(htmlDoc.select("body").html());

            worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(bodyContent.getBytes(charset))
                    , new  ByteArrayInputStream(DefaultStyle.DEFAULT_ORDER_CSS.getBytes())
                    ,charset
                    , new AsianFontProvider(FONT_PATH,BD_FONT_PATH));
            document.close();



    }
    public static void createWithHtml(String templateString,String extraHtml, OutputStream outputStream) throws Exception{
//            Document document = new Document(PageSize.A4);
            Document document = new Document(new RectangleReadOnly(1191F,842F));

            PdfWriter pdfWriter = PdfWriter.getInstance(document,
                    outputStream);
            if(null==extraHtml){
                extraHtml = "";
            }
            document.open();
//            document.addAuthor("1+1");
//            document.addCreator("1+1");
//            document.addSubject("电子合同");
            document.addCreationDate();
//            document.addTitle("电子合同");

            XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
            String mdContent = templateString;
            PegDownProcessor pdp = new PegDownProcessor(Extensions.ALL);
//            mdContent = getTemplateString(mdContent,dto);
            String htmlContent = "<html lang=\"en\"><meta http-equiv=\"Content-Type\" content=\"text/html; charset="+charset.name()+"\" /><body>" + templateString + "</body></html>";
            org.jsoup.nodes.Document htmlDoc = Jsoup.parse(htmlContent, "", Parser.xmlParser());
/*            Element element = htmlDoc.selectFirst("table");
            Elements centerEle = htmlDoc.select("center");
            //处理center标签
            if(centerEle!=null){
                for(Element center:centerEle){
                    Element parent = center.parent();
                    String text = center.text();
                    center.remove();
                    parent.text(text);
                    parent.attr("align","center");
                    parent.attr("style","margin:0 auto;text-align:center;");
                }

            }*/
/*            if(element!=null){
                //处理表格宽度问题
                Elements elements = element.select("th");
                for (int i = 0; i < elements.size(); i++) {
                    if (i < colWidth.length) {
                        elements.get(i).attr("width", colWidth[i]);
                    }
                }
            }*/

            //处理h1~h6问题
            Elements aList = htmlDoc.select("h1 a,h2 a,h3 a,h4 a,h5 a,h6 a");
            for (Element a : aList) {
                String text = a.text();
                a.text("");
                a.appendElement("strong");
                a.child(0).text(text);
            }
            String bodyContent = htmlDoc.select("body").html();
            if(extraHtml!=null){
                bodyContent =  bodyContent + extraHtml;
                bodyContent = bodyContent.replaceAll("\t","").replaceAll("\n","");
            }
            log.debug("生产pdf原始html内容：{}",htmlDoc.select("html").html());
        System.out.println(htmlDoc.select("body").html());

            worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(bodyContent.getBytes(charset))
                    , new  ByteArrayInputStream(DefaultStyle.DEFAULT_ORDER_CSS.getBytes())
                    ,charset
                    , new AsianFontProvider(FONT_PATH,BD_FONT_PATH));
            document.close();



    }

    public static String change(double v) {
        if (v < 0 || v > MAX_VALUE){
            return "参数非法!";
        }
        long l = Math.round(v * 100);
        if (l == 0){
            return "零元整";
        }
        String strValue = l + "";
        // i用来控制数
        int i = 0;
        // j用来控制单位
        int j = UNIT.length() - strValue.length();
        String rs = "";
        boolean isZero = false;
        for (; i < strValue.length(); i++, j++) {
            char ch = strValue.charAt(i);
            if (ch == '0') {
                isZero = true;
                if (UNIT.charAt(j) == '亿' || UNIT.charAt(j) == '万' || UNIT.charAt(j) == '元') {
                    rs = rs + UNIT.charAt(j);
                    isZero = false;
                }
            } else {
                if (isZero) {
                    rs = rs + "零";
                    isZero = false;
                }
                rs = rs + DIGIT.charAt(ch - '0') + UNIT.charAt(j);
            }
        }
        if (!rs.endsWith("分")) {
            rs = rs + "整";
        }
        rs = rs.replaceAll("亿万", "亿");
        return rs;
    }

}
